package com.whpost.service.zhdt.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.whpost.service.entity.t.TCzy;
import com.whpost.service.entity.t.TRole;
import com.whpost.service.entity.t.TXzjg;
import com.whpost.service.entity.t.TreeNode;
import com.whpost.service.entity.tools.ListInfo;
import com.whpost.service.entity.tools.PageInfo;
import com.whpost.service.entity.tools.ResultInfo;
import com.whpost.service.service.BaseServices;
import com.whpost.service.service.t.TApiNonceService;
import com.whpost.service.service.t.TXzjgServices;
import com.whpost.service.tools.ToolBean;
import com.whpost.service.zhdt.dao.ZhdtWgxxMapper;
import com.whpost.service.zhdt.entity.ZhdtWgxx;
import com.whpost.service.zhdt.entity.ZhdtWgxxKhxx;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ZhdtWgxxServices extends BaseServices<ZhdtWgxxMapper, ZhdtWgxx> {

    @Resource
    private ZhdtWgfzServices zhdtWgfzServices;
    @Resource
    private TXzjgServices tXzjgServices;
    @Resource
    private TApiNonceService tApiNonceService;

    @Override
    public ResultInfo save(String loginId, Map<String, Object> map) {
        JSONObject jsonObject = getData(map,loginId);
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            String lx="",id="",nonce_ms="",nonce_zhi="",fenceDataStr="",wgfz="",xzjg="",wgmc="";
            if (jsonObject.containsKey("lx")) {
                lx = jsonObject.getString("lx");
            }
            if (jsonObject.containsKey("id")) {
                id = jsonObject.getString("id");
            }
            if (jsonObject.containsKey("wgfz")) {
                wgfz = jsonObject.getString("wgfz");
            }
            if (jsonObject.containsKey("xzjg")) {
                xzjg = jsonObject.getString("xzjg");
            }
            if (jsonObject.containsKey("wgmc")) {
                wgmc = jsonObject.getString("wgmc");
            }
            if (jsonObject.containsKey("fenceData")) {
                fenceDataStr = jsonObject.getString("fenceData");
            }
            if (jsonObject.containsKey("nonce_ms")) {
                nonce_ms = jsonObject.getString("nonce_ms");
            }
            if (jsonObject.containsKey("nonce_zhi")) {
                nonce_zhi = jsonObject.getString("nonce_zhi");
            }
            //参数校验
            if (StringUtils.isEmpty(wgfz)){
                return new ResultInfo(500,"所属分组丢失！",null);
            }
            if (StringUtils.isEmpty(xzjg)){
                return new ResultInfo(500,"所属机构丢失！",null);
            }
            if (StringUtils.isEmpty(wgmc)){
                return new ResultInfo(500,"网格名称丢失！",null);
            }
            if (StringUtils.isEmpty(fenceDataStr)){
                return new ResultInfo(500,"网格信息丢失！",null);
            }

            //ToolBean.info("fenceData:"+fenceDataStr);

            // 转换为JSON对象
            JSONObject fenceData = JSONObject.parseObject(fenceDataStr);

            // 2. 提取currentPath数组
            JSONArray currentPath = fenceData.getJSONArray("currentPath");

            // 3. 转换为JSON字符串（用于存入数据库wglj字段）
            String wglj = currentPath.toJSONString();

            // 4. 其他需要的字段提取（根据实际需求）
            String bkYsdm = fenceData.getString("color"); // 边框颜色

            //ToolBean.info("网格的路径："+wglj);


            //校验nonce
            ResultInfo ResultInfoCheckNonce = new ResultInfo();
            ResultInfoCheckNonce = tApiNonceService.checkNonce(nonce_ms,loginId,nonce_zhi,"新增网格！");

            if (ResultInfoCheckNonce.getCode()!=200)
            {
                return ResultInfoCheckNonce;
            }

            TCzy tCzy = gettCzyDao().selectById(loginId);

            ZhdtWgxx zhdtWgxx = new ZhdtWgxx();


            if ("1".equals(lx)){
                zhdtWgxx = getBaseMapper().selectById(id);
            }

            zhdtWgxx.setWgfzId(Long.parseLong(wgfz));
            zhdtWgxx.setXzjgId(Long.parseLong(xzjg));
            zhdtWgxx.setWgmc(wgmc);
            zhdtWgxx.setWglj(wglj);
            zhdtWgxx.setBkYsdm(bkYsdm);

            if ("0".equals(lx)){
                zhdtWgxx.setAddRq(ToolBean.getToday());
                zhdtWgxx.setTCzyId(tCzy.getId());
            }

            ResultInfo resultInfo;
            if ("1".equals(lx)){
                if (!String.valueOf(zhdtWgxx.getTCzyId()).equals(loginId) && !"1".equals(loginId)){
                    return new ResultInfo(500,"非自己维护的网格信息不得修改！",null);
                }
                getBaseMapper().updateById(zhdtWgxx);
                resultInfo = new ResultInfo(1, "修改成功！",zhdtWgxx);
            }else{
                getBaseMapper().insert(zhdtWgxx);
                resultInfo = new ResultInfo(1, "新增成功！",zhdtWgxx);
            }
            return backRtn(resultInfo,loginId);
        }
    }

    @Override
    public ResultInfo info(String loginId, Map<String, Object> map) {
        JSONObject jsonObject = getData(map,loginId);
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            TCzy tCzy = new TCzy();
            tCzy = gettCzyDao().selectById(loginId);

            Map<String,Object> infoMap = new HashMap<>();

            String id="";
            if (jsonObject.containsKey("id")) {
                id = jsonObject.getString("id");
            }
            String lx="";
            if (jsonObject.containsKey("lx")) {
                lx = jsonObject.getString("lx");
            }

            if ("1".equals(lx)){
                ZhdtWgxx zhdtWgxx = new ZhdtWgxx();
                zhdtWgxx = getBaseMapper().selectById(id);
                infoMap.put("zhdtWgxx",zhdtWgxx);
            }

            List<TreeNode> tXzjgTree = tXzjgServices.getTreeSelect(null);
            infoMap.put("tXzjgTree",tXzjgTree);

            List<TreeNode> zhdtWgfzTree = zhdtWgfzServices.getTreeSelect(null);
            infoMap.put("zhdtWgfzTree",zhdtWgfzTree);

            //给出默认值

            ResultInfo resultInfo = new ResultInfo(0, "成功返回！",infoMap);
            return backRtn(resultInfo,loginId);
        }
    }

    @Override
    public ResultInfo query(String loginId, Map<String, Object> map) {
        try {
            JSONObject jsonObject = getData(map, loginId);
            if (StringUtils.isEmpty(loginId)) {
                return new ResultInfo(500, "用户信息丢失！", null);
            } else {
                // 声明参数变量（新增xzjgIds和wgfzIds）
                String curpage = "", pagesize = "", wgmc = "", state = "";
                JSONArray xzjgIdsArr = null; // 存储xzjgIds数组
                JSONArray wgfzIdsArr = null; // 存储wgfzIds数组

                QueryWrapper<ZhdtWgxx> queryWrapper = new QueryWrapper<>();

                // 提取已有参数
                if (jsonObject.containsKey("curpage")) {
                    curpage = jsonObject.getString("curpage");
                }
                if (jsonObject.containsKey("pagesize")) {
                    pagesize = jsonObject.getString("pagesize");
                }
                if (jsonObject.containsKey("wgmc")) {
                    wgmc = jsonObject.getString("wgmc");
                }
                if (jsonObject.containsKey("state")) {
                    state = jsonObject.getString("state");
                }

                // 提取新增的xzjgIds和wgfzIds（数组类型）
                if (jsonObject.containsKey("xzjgIds")) {
                    xzjgIdsArr = jsonObject.getJSONArray("xzjgIds");
                }
                if (jsonObject.containsKey("wgfzIds")) {
                    wgfzIdsArr = jsonObject.getJSONArray("wgfzIds");
                }

                // 处理分页默认值
                if (StringUtils.isEmpty(curpage)) curpage = "1";
                if (StringUtils.isEmpty(pagesize)) pagesize = "10";
                Page<ZhdtWgxx> page = new Page<>(Integer.parseInt(curpage), Integer.parseInt(pagesize));

                // 构建查询条件
                if (!StringUtils.isEmpty(wgmc)) {
                    queryWrapper.like("wgmc", wgmc);
                }
                if (!StringUtils.isEmpty(state)) {
                    queryWrapper.eq("state", state);
                }

                // 处理xzjgIds查询（IN条件）
                if (xzjgIdsArr != null && !xzjgIdsArr.isEmpty()) {
                    // 转换JSONArray为List<Integer>
                    List<Integer> xzjgIdsList = new ArrayList<>();
                    for (int i = 0; i < xzjgIdsArr.size(); i++) {
                        xzjgIdsList.add(xzjgIdsArr.getIntValue(i));
                    }
                    // 添加IN条件（假设数据库字段为xzjg_id，需根据实际表结构调整）
                    queryWrapper.in("xzjg_id", xzjgIdsList);
                }

                // 处理wgfzIds查询（IN条件）
                if (wgfzIdsArr != null && !wgfzIdsArr.isEmpty()) {
                    // 转换JSONArray为List<Integer>
                    List<Integer> wgfzIdsList = new ArrayList<>();
                    for (int i = 0; i < wgfzIdsArr.size(); i++) {
                        wgfzIdsList.add(wgfzIdsArr.getIntValue(i));
                    }
                    // 添加IN条件（假设数据库字段为wgfz_id，需根据实际表结构调整）
                    queryWrapper.in("wgfz_id", wgfzIdsList);
                }

                // 其他基础条件
                queryWrapper.eq("1", "1"); // 占位条件（可删除）
                queryWrapper.orderByDesc("id");

                // 执行分页查询
                IPage<ZhdtWgxx> pages = getBaseMapper().getZhtdWgxxPage(page, queryWrapper);

                // 封装返回结果
                PageInfo pageInfo = new PageInfo();
                pageInfo.setTotal(pages.getTotal());
                pageInfo.setCurPage(pages.getCurrent());
                pageInfo.setPageSize(pages.getSize());
                pageInfo.setPageTotal(pages.getPages());

                ListInfo<ZhdtWgxx> listInfo = new ListInfo<>();
                listInfo.setPageInfo(pageInfo);
                listInfo.setListInfo(pages.getRecords());
                listInfo.setUserId(loginId);

                // 查询条件回显
                Map<String, Object> cxtjMap = new HashMap<>();
                cxtjMap.put("wgmc", wgmc);
                cxtjMap.put("state", state);
                cxtjMap.put("xzjgIds", xzjgIdsArr); // 回显xzjgIds
                cxtjMap.put("wgfzIds", wgfzIdsArr); // 回显wgfzIds

                Map<String, Object> rtnMap = new HashMap<>();
                rtnMap.put("cxjg", listInfo);
                rtnMap.put("cxtj", cxtjMap);

                ResultInfo resultInfo = new ResultInfo(0, "成功返回！", rtnMap);
                return backRtn(resultInfo, loginId);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ResultInfo resultInfo = new ResultInfo(500, "发生错误！", null);
            return backRtn(resultInfo, loginId);
        }
    }

    @Override
    @Transactional
    public ResultInfo del(String loginId, Map<String, Object> map) {
        JSONObject jsonObject = getData(map,loginId);
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            String id = "";
            if (jsonObject.containsKey("id")) {
                id = jsonObject.getString("id");
            }

            ZhdtWgxx zhdtWgxx = new ZhdtWgxx();
            zhdtWgxx = getBaseMapper().selectById(id);

            if (null==zhdtWgxx){
                return new ResultInfo(500,"网格信息不存在！",null);
            }

            if (!String.valueOf(zhdtWgxx.getTCzyId()).equals(loginId) && !"1".equals(loginId)){
                return new ResultInfo(500,"非自己维护的网格信息不得修改！",null);
            }

            //暂时没有其它判断

            getBaseMapper().deleteById(id);
            return new ResultInfo(3,"删除成功！",null);
        }
    }
}
